package com.study.aliyun.datawork;

import com.study.util.FileUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @version V1.0
 * @title: DBUtil
 * @description: ${DESCRIPTION}
 * @author: wanghuilong
 * @date: 2020-06-10 18:03
 * @copyright: http://fingo.com.my/
 */
public class DBUtil {

//    // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
//    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//    static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";

    //MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3308/information_schema?useSSL=false&serverTimezone=UTC";

    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "fingo";
    static final String PASS = "cDW5bbEu8bKv";

    static Connection conn = null;
    static Statement stmt = null;
    static ResultSet rs = null;

    public static void init() {
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<String> tables = Arrays.asList("t_od_base", "t_od_activity", "t_od_member", "t_od_address"
            , "t_od_after", "t_od_after_product", "t_od_products", "t_od_product_advance", "t_od_suborder", "t_od_sub_products"
            , "t_in_exchange_currency", "t_in_exchange_rate", "t_at_active", "t_pd_spu", "t_pm_user_coupon"
            , "t_py_account_detail", "t_py_order_pay_info", "t_pd_advance_sale", "t_od_coupon", "t_pd_sku", "t_pd_category"
            , "t_pd_sku_country", "t_pd_spu_country", "t_erp_supplier", "t_mb_member_information", "t_mb_user",
            "t_pd_sku_country_snapshot",
            "t_erp_purchase_order",
            "t_erp_purchase_sale_order_ref",
            "t_erp_logi_tracking_info",
            "t_erp_income_order",
            "t_erp_out_order",
            "t_erp_logi_tracking_info",
            "t_erp_out_order_detail",
            "t_erp_income_order_ref",
            "t_erp_address", "t_erp_warehouse", "t_erp_overall_target", "t_erp_leg_target");

    static List<String> checkSql = new ArrayList<>();

    static List<String> dropTableSql = new ArrayList<>();

    public static void main(String[] args) {
        init();
        List<String> list = new ArrayList<>();

        for (int i = 0; i < tables.size(); i++) {
            String tableName = tables.get(i);
            try {
                String sql = "SELECT table_name, table_comment FROM tables" +
                        " where TABLE_NAME = '" + tableName + "' and TABLE_SCHEMA = 'datacenter'";
                rs = stmt.executeQuery(sql);
                boolean key = false;
                // 展开结果集数据库
                while (rs.next()) {
                    // 通过字段检索
                    String table_name = rs.getString(1);
                    String table_comment = rs.getString(2);
                    String ods = createOdsTableSql(tableName, table_comment, "ods", "df");
                    list.add(ods);
                    key = true;
                }
                if (!key) {
                    System.out.println("没有查到数据：" + tableName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        close();
        FileUtil.writeToFileByLine(list, "src/main/resources/file/table.sql");
        System.out.println("tables:" + tables.size() + ",sqlsize:" + list.size());
        for (int i = 0; i < checkSql.size(); i++) {
            System.out.println(checkSql.get(i));
        }

        for (int i = 0; i < dropTableSql.size(); i++) {
            System.out.println(dropTableSql.get(i));
        }
    }

    public static String createOdsTableSql(String tableName, String tableComment, String prefix, String stuffix) {
        StringBuilder stringBuilder = new StringBuilder();
        String newTableName = createNewTableName(tableName);
        newTableName = prefix + "_" + newTableName + "_" + stuffix;
        stringBuilder.append("drop table ").append(newTableName).append(";").append("\n");
        dropTableSql.add("drop table " + newTableName + ";");
        stringBuilder.append("CREATE TABLE ").append(newTableName).append("\n");
        stringBuilder.append("(").append("\n");
        checkSql.add("select count(*) from " + newTableName + ";");
        List<String> rows = new ArrayList<>();
        try {
            String sql = "select COLUMN_NAME, DATA_TYPE AS `数据类型`,COLUMN_COMMENT from COLUMNS where " +
                    "TABLE_NAME = '" + tableName + "' and TABLE_SCHEMA = 'datacenter'";
            rs = stmt.executeQuery(sql);
            // 展开结果集数据库
            while (rs.next()) {
                // 通过字段检索
                String colName = rs.getString(1);
                String type = rs.getString(2);
                String content = rs.getString(3);
                content = content.replaceAll(":", " ").replaceAll(";", " ");
                StringBuilder row = new StringBuilder();
                row.append(" ").append(colName).append(" ").append(coverType(type))
                        .append(" ").append("COMMENT").append(" ").append("'").append(content).append("'");
                rows.add(row.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0; i < rows.size(); i++) {
            stringBuilder.append(rows.get(i));
            if (i != (rows.size() - 1)) {
                stringBuilder.append(",");
            }
            stringBuilder.append("\n");
        }
        stringBuilder.append(")").append("\n").append("COMMENT \"").append(tableComment).append("\"\n")
                .append("PARTITIONED BY (ds string)\n")
                .append("stored as orcfile;");
        return stringBuilder.toString();
    }

    private static String createNewTableName(String tableName) {
        StringBuilder stringBuilder = new StringBuilder();
        String[] s = tableName.split("_");
        if (s.length >= 3) {
            String base = s[1];
            switch (base.trim()) {
                case "od":
                    stringBuilder.append("order");
                    break;
                case "in":
                    stringBuilder.append("i18n");
                    break;
                case "py":
                    stringBuilder.append("polypay");
                    break;
                case "at":
                    stringBuilder.append("activity");
                    break;
                case "pm":
                    stringBuilder.append("promotion");
                    break;
                case "pd":
                    stringBuilder.append("product");
                    break;
                case "erp":
                    stringBuilder.append("erp");
                    break;
                case "mb":
                    stringBuilder.append("member");
                    break;
                default:
                    System.out.println("未找到匹配表名：" + tableName);
                    break;
            }
        } else {
            System.out.println("非法表名：" + tableName);
        }
        return stringBuilder.append("_").append(tableName).toString();
    }

    /**
     * 整数类	INT、TINYINT、SMALLINT、MEDIUMINT和BIGINT
     * 浮点类	FLOAT、DOUBLE和DECIMAL
     * 字符串类	VARCHAR、CHAR、TINYTEXT、TEXT、MEDIUMTEXT和LONGTEXT
     * 日期时间类	DATE、DATETIME、TIMESTAMP、TIME和YEAR
     * 布尔型	BIT和BOOL
     * 二进制类	TINYBLOB、MEDIUMBLOB、BLOB、LONGBLOB和VARBINARY
     *
     * @param type
     * @return
     */
    private static String coverType(String type) {
        String dataType = type.trim().toUpperCase();
        switch (dataType) {
            case "INT":
            case "TINYINT":
            case "SMALLINT":
            case "MEDIUMINT":
            case "BIGINT":
                return "BIGINT";
            case "FLOAT":
            case "DOUBLE":
            case "DECIMAL":
                return "DOUBLE";
            case "VARCHAR":
            case "CHAR":
            case "TINYTEXT":
            case "TEXT":
            case "MEDIUMTEXT":
            case "LONGTEXT":
                return "STRING";
            case "DATE":
            case "DATETIME":
            case "TIMESTAMP":
            case "TIME":
            case "YEAR":
                return "TIMESTAMP";
            case "BIT":
            case "BOOL":
                return "BOOLEAN";
        }
        return "";
    }

    public static void close() {
        try {
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se2) {
            }// 什么都不做
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}
